#include <iostream>
#include "opencv2/opencv.hpp"
#include "face.h"
#include <cstring>
#include <chrono>
#include <ctime>

using namespace std;
using namespace cv;
using namespace aip;

int main()
{
    // 加载人脸检测分类器
    CascadeClassifier Classifier("/usr/share/opencv/haarcascades/haarcascade_frontalface_alt2.xml");
    if (!Classifier.load("/usr/share/opencv/haarcascades/haarcascade_frontalface_alt2.xml")) {
        cout << "Classifier load failed!" << endl;
        return -1;
    }

    std::string app_id = "115637414";
    std::string api_key = "LuqtWCeWeloiEORqM7cuvMfi";
    std::string secret_key = "G1VvB3dQY4C0Spr85ReYN9gGs9lgVnYO";
    aip::Face client(app_id, api_key, secret_key);

    Mat ColorImage = imread("/home/makeru/1.jpg"); // 读取指定路径的图片
    if (ColorImage.empty()) {
        cout << "Image load failed!" << endl;
        return -1;
    }

    Mat GrayImage;
    vector<Rect> Allface;
    Mat MatFace;
    vector<uchar> JpgFace;
    string Base64Face;
    Json::Value result;

    std::string image_type = "BASE64";
    Json::Value jsonMap;
    auto now = chrono::system_clock::now();
    char buffer[26];

    // 转换为时间_t
    time_t now_time_t = chrono::system_clock::to_time_t(now);
    ctime_r(&now_time_t, buffer);

    // 将图像转换为灰度并进行均衡化
    cvtColor(ColorImage, GrayImage, COLOR_BGR2GRAY);
    equalizeHist(GrayImage, GrayImage);

    // 检测人脸
    Classifier.detectMultiScale(GrayImage, Allface, 1.1, 3, 0 | CASCADE_SCALE_IMAGE, Size(30, 30));

    if (Allface.size()) {
        rectangle(ColorImage, Allface[0], Scalar(255, 255, 255));
        MatFace = GrayImage(Allface[0]);
        imencode(".jpg", MatFace, JpgFace);

        Base64Face = base64_encode((char*)JpgFace.data(), JpgFace.size());
        result = client.face_search_v3(Base64Face, image_type, "zyf", jsonMap);

        if (!result["result"].isNull()) {
            if (result["result"]["user_list"][0]["score"].asInt() > 80) {
                cout << result["result"]["user_list"][0]["user_id"] << endl;
                cout << buffer << endl;
            }
        }
    }

    // 显示结果图像
    // imshow("Detected Face", ColorImage);
    // waitKey(0);

    return 0;
}